package com.wqnmdb.im.utils;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池工具类
 */
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class ThreadPoolUtil {
    /**
     * 线程池核心线程数
     */
    private static final int CORE_POOL_SIZE = 5;

    /**
     * 线程池最大线程数
     */
    private static final int MAX_POOL_SIZE = 10;

    /**
     * 任务队列  此处使用ArrayBlockingQueue有界队列，防止队列无限膨胀导致内存溢出
     */
    private static final BlockingQueue WORK_QUEUE = new ArrayBlockingQueue(20);

    /**
     * 超出核心线程的额外线程空状态生存时间  此处是秒
     */
    private static final int KEEP_ALIVE_TIME = 60;

    /**
     * 线程工厂
     */
    private static final ThreadFactory THREAD_FACTORY = new MyThreadFactory();

    /**
     * 拒绝策略 CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
     */
    private static final RejectedExecutionHandler REJECTED_HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();

    /**
     * 线程池
     */
    private static volatile ThreadPoolExecutor threadPool;

    static {
        threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE,
                KEEP_ALIVE_TIME, TimeUnit.SECONDS, WORK_QUEUE, THREAD_FACTORY, REJECTED_HANDLER);
    }

    public static void execute(Runnable runnable) {
        threadPool.execute(runnable);
    }

    public static void execute(FutureTask futureTask) {
        threadPool.execute(futureTask);
    }

    public static void cancel(FutureTask futureTask) {
        futureTask.cancel(true);
    }

    /**
     * 自定义线程工厂
     */
    static class MyThreadFactory implements ThreadFactory {
        private final AtomicInteger threadId = new AtomicInteger();

        /**
         * 设置线程名称
         */
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "ThreadPoolUtil:" + threadId.getAndIncrement());
        }
    }
}

